const hx = require("hbuilderx");
const {
	setUploadServeDataPath
} = require('../options.js');
const {
	exec
} = require('child_process');
const sendFile = require('../utils/sendFile');
const checkFile = require('../utils/checkFile');
const {
	getAppRoot,
	getWorkspaceFolderData,
	getManifestData
} = require('../utils/hx');
const toSetUploadServe = require('./setUploadServe');

function BuildPackager() {
	this.timer = null;
	this.timer2 = null;
	this.seconds = 0;
	this.myStatusBarItem = null
}

BuildPackager.prototype.build = async function(type) {
	try {
		this.clearTimer();

		const [appid, versionName, versionCode] = await getManifestData(['appid', 'versionName',
		'versionCode']);
		if (!appid || !versionName || !versionCode) {
			throw new Error('Manifest data is incomplete');
		}

		const uploadServeJson = await this.getUploadServeJson(appid, type);
		if (uploadServeJson.code === '-1' || !uploadServeJson.data) {
			hx.window.showInformationMessage('请先设置服务器信息');
			toSetUploadServe(type);
			return;
		}

		const fileName = `${versionName}_${versionCode}.wgt`;
		const projectName = await getWorkspaceFolderData('name');
		const execArg = await this.getExecArg(type, fileName, projectName);

		this.myStatusBarItem = hx.window.createStatusBarItem(
			hx.StatusBarAlignment.Right,
			9999,
		)

		const activeFolderPath = (await getWorkspaceFolderData('uri')).path.replace(/^\//, '');
		this.startTimer(type, projectName);
		await this.execHandler(execArg, type, fileName, activeFolderPath);
		// 等待2s再发送
		await sleep(2000)
		await this.sendFile(type, uploadServeJson.data, fileName, activeFolderPath)

		this.showSuccessMessage(type, uploadServeJson.data, fileName);
		hx.window.setStatusBarMessage(`${projectName}自动打包完成，用时: ${this.seconds} 秒`, 5000, 'info');
		this.clearTimer();

	} catch (e) {
		console.log(e);
		this.clearTimer();
		hx.window.showWarningMessage(e.message || e);
	}
};

BuildPackager.prototype.clearTimer = function() {
	this.seconds = 0
	this.myStatusBarItem && this.myStatusBarItem.hide()
	if (this.timer) {
		clearInterval(this.timer);
		this.timer = null;
	}
	if (this.timer2) {
		clearInterval(this.timer2)
		this.timer2 = null
	}
};

BuildPackager.prototype.getUploadServeJson = async function(appid, type) {
	return await hx.util.readJSONValue(setUploadServeDataPath, appid + (type === 'h5' ? 'h5' : ''));
};

BuildPackager.prototype.getExecArg = async function(type, fileName, projectName) {
	//  --host HBuilderX-extension
	if (type === 'h5') {
		return `${getAppRoot()}/cli.exe publish --platform h5 --project ${projectName}`;
	} else {
		return `${getAppRoot()}/cli.exe publish --platform APP --type wgt --project ${projectName} --name ${fileName}`;
	}
};

BuildPackager.prototype.startTimer = async function(type, projectName) {
	this.myStatusBarItem.text = `${projectName}正在自动打包${type}`
	this.myStatusBarItem.show()

	this.timer = setInterval(() => {
		this.seconds++;
		hx.window.setStatusBarMessage(`${projectName}正在自动打包${type}，已用时: ${this.seconds} 秒`, 5000, type == 'h5' ? 'info' :
			'info');
	}, 1000);

};

BuildPackager.prototype.execHandler = async function(command, type, fileName, activeFolderPath) {
	const checkFilePath = type == 'h5' ? `${activeFolderPath}/unpackage/dist/build/web/index.html` :
		`${activeFolderPath}/unpackage/release/${fileName}`,
		currentTime = new Date().getTime()

	// console.log(checkFilePath)
	return new Promise((resolve, reject) => {
		const process = exec(command, {
			encoding: 'binary'
		}, async (err, res) => {
			if (err) reject(err);
		});

		// 部分版本的cli不会吐出【打包成功xxx】
		// process.stdout.on('data', (res) => {
		//     if (res.includes('³É¹¦£¬Â·¾¶Îª£º')) resolve();
		// });

		// 读取文件来判断是否打包成功
		this.timer2 = setInterval(async () => {
			const res = await checkFile(checkFilePath, currentTime)
			if (res) {
				clearInterval(this.timer2)
				resolve()
			}
		}, 1000)
	});
};

BuildPackager.prototype.sendFile = async function(type, uploadServeData, fileName, activeFolderPath) {
	const sendFilePath = type == 'h5' ? `${activeFolderPath}/unpackage/dist/build/web` :
		`${activeFolderPath}/unpackage/release/${fileName}`
	// 上传服务器
	// console.log('上传', sendFilePath, uploadServeData)
	await sendFile(sendFilePath, uploadServeData, type == 'h5', true)
};

BuildPackager.prototype.showSuccessMessage = async function(type, uploadServeData, fileName) {
	const message = await hx.window.showInformationMessage(`打包成功、上传成功，用时${this.seconds}秒`, [type === 'wgt' && uploadServeData.domain ?
		'复制链接' : '知道了'
	]);
	if (type === 'wgt' && message === '复制链接') {
		hx.env.clipboard.writeText(`${uploadServeData.domain}${fileName}`);
	}
};

function sleep(delay = 2000) {
	return new Promise(resolve => {
		setTimeout(() => {
			resolve()
		}, delay)
	})
}

module.exports = BuildPackager;